package com.jamiexu.help.test;

import java.net.*;
import java.io.*;
import java.nio.charset.*;
public class SocketUtils
{
	public static String getData(Socket socket){
		try
		{
			InputStream inputStream = socket.getInputStream();
			//System.out.println(inputStream.available());
			byte[] lenByte = new byte[4];
			inputStream.read(lenByte);
			int len = new DataInputStream(new ByteArrayInputStream(lenByte)).readInt();
			byte[] dataByte = new byte[len];
			inputStream.read(dataByte,0,len); 
			return new String(dataByte,0,len,StandardCharsets.UTF_8);
		}
		catch (IOException e)
		{
			e.fillInStackTrace();
		}
		return null;
	}
	
	
	public static void sendData(Socket socket,String con){
		try
		{
			OutputStream out = socket.getOutputStream();
			DataOutputStream datao = new DataOutputStream(out);
			byte[] data = con.getBytes(StandardCharsets.UTF_8);
			System.out.println("byte length:"+data.length);
			datao.writeInt(data.length);
			out.write(data);
			out.flush();
		}
		catch (IOException e)
		{
			e.printStackTrace();
		}

	}
	
}
